<?php
/**
 *数组帮助方法类
 *
 */
class Helper_Array{




	/**
	 * 获取一个数组元素(如果元素不存在返回设置的默认值)
	 *
	 *
	 * @param	string
	 * @param	array
	 * @param	mixed
	 * @return	mixed	depends on what the array contains
	 */
	public static function element($item, array $array, $default = NULL)
	{
		return array_key_exists($item, $array) ? $array[$item] : $default;
	}


// ------------------------------------------------------------------------


	/**
	 * Random Element - Takes an array as input and returns a random element
	 *
	 * @param	array
	 * @return	mixed	depends on what the array contains
	 */
	public static  function random_element($array)
	{
		return is_array($array) ? $array[array_rand($array)] : $array;
	}


// --------------------------------------------------------------------


	/**
	 * 批量获取数组元素(如果元素不存在，返回设置的默认值)
	 *
	 *
	 * @param	array
	 * @param	array
	 * @param	mixed
	 * @return	mixed	depends on what the array contains
	 */
	public static function elements($items, array $array, $default = NULL)
	{
		$return = array();

		is_array($items) OR $items = array($items);

		foreach ($items as $item)
		{
			$return[$item] = array_key_exists($item, $array) ? $array[$item] : $default;
		}

		return $return;
	}

	public static function filterModels(&$data){

		unset($data['module'], $data['controller'], $data['action']);
		return false;
	}

	public static function du($data, $exit = true){

		echo '<pre>';
		var_dump($data);
		if($exit) exit;
	}

	public static function pr($data, $exit = true){

		echo '<pre>';
		print_r($data);
		if($exit) exit;
	}

	/**
	 * 非递归树状输出结构
	 * @param 数组
	 * @return array();
	 */
	public static function getTreesByForeach($data, $pidName = 'parent_id'){

		$tree = [];
		$treeMap = [];
		foreach($data as $item){
			$treeMap[$item['id']] = $item;
		}
		foreach($data as $item){
			if(isset($treeMap[$item[$pidName]])){
				$treeMap[$item[$pidName]]['children'] = &$treeMap[$item['id']];
			}else{
				$tree[] = &$treeMap[$item['id']];
			}
		}
		unset($treeMap);
		return $tree;
	}

	/**
	 * 递归树状输出HTML(option)
	 * @param 数组
	 * @return array();
	 */
	public static function getTreesByForeachHtml($data, $pid = 0, $tag = 0){

		static $str = '<select>';
		$tag ++;
		foreach($data as $item){
			$tagstr = str_repeat('--', $tag) . '|';
			if($pid == 0){
				$tag = 0;
				$tagstr = '';
			}
			if($item['parent_id'] == $pid){
				$str .= '<option data-id="' . $item['id'] . '" data-parent_id="' . $item['parent_id'] . '">' . $tagstr . $item['name_ch'] . '</option>';
				self::getTreesByForeachHtml($data, $item['id'], $tag);
			}
		}
		unset($data);
		return $str;
	}
}